package  {
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import gs.TweenLite;
	import utils.GlobalConfig;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class Preloader extends MovieClip {
		
		//{ region Stage elements
		
		public var logo:MovieClip;
		
		//} endregion
		
		private var background:MovieClip;
		private var duration:Number = 0.4;
		
		public function Preloader() {
			this.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
		}
		
		private function addedToStage(event:Event):void {
			init();
		}
		
		private function init():void {
			initListeners();
		}
		
		private function initListeners():void {
			
		}
		
		private function drawBackground(width:Number, height:Number):void {
			background = new MovieClip();
			background.graphics.beginFill(GlobalConfig.STAGE_COLOR, 0.7);
			background.graphics.drawRect( -width / 2, -height / 2, width, height);
			this.addChildAt(background, 0);
		}
		
		public function setTarget(target:MovieClip):void {
			if (target.getChildByName("preloader") == null) {
				drawBackground(target.width, target.height);
				logo.alpha = 0;
				logo.scaleX = logo.scaleY = 0;
				logo.x = (background.width - logo.width) / 2;
				logo.y = (background.height - logo.height) / 2;
				this.name = "preloader";
				
				target.addChild(this);
				TweenLite.to(logo, duration, { alpha:1, scaleX:1, scaleY:1, onComplete:setTarget_Complete } );
			}
		}
		
		public function removeTarget(target:MovieClip):void {
			if (target.getChildByName("preloader") != null) {
				TweenLite.to(logo, duration, { alpha:0, scaleX:0, scaleY:0, onComplete:removeTarget_Complete, onCompleteParams:[target] } );
			}
		}
		
		//{ region Animation
		
		private function setTarget_Complete():void {
			logo.gotoAndPlay(0);
		}
		
		private function removeTarget_Complete(target:MovieClip):void {
			this.removeChild(background);
			target.removeChild(this);
		}
		
		//} endregion
	}
	
}